package y_2025.m05.d23.test;

import java.util.LinkedList;
import java.util.Queue;

class SharedBuffer {
    private final Queue<Integer> buffer = new LinkedList<>();
    private final int maxSize;
    
    public SharedBuffer(int size) {
        this.maxSize = size;
    }
    
    // 生产数据
    public synchronized void produce(int item) throws InterruptedException {
        while (buffer.size() == maxSize) {
            System.out.println("缓冲区满，生产者等待...");
            wait(); // 缓冲区满时等待
        }
        
        buffer.add(item);
        System.out.println("生产: " + item + "，缓冲区大小: " + buffer.size());
        notifyAll(); // 通知消费者
    }
    
    // 消费数据
    public synchronized void consume() throws InterruptedException {
        while (buffer.isEmpty()) {
            System.out.println("缓冲区空，消费者等待...");
            wait(); // 缓冲区空时等待
        }
        
        int item = buffer.poll();
        System.out.println("消费: " + item + "，缓冲区大小: " + buffer.size());
        notifyAll(); // 通知生产者
    }
}